﻿using DevelopTool.Common;
using DevelopTool.Model;
using LiteDB;
using Sunny.UI;
using System;
using System.IO;

namespace DevelopTool.Bll.LocalDbBlls
{
    /// <summary>
    /// 本地用户业务
    /// </summary>
    public class LocalUserBll
    {
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public Tuple<int, string> Loging(string dbFile, string password)
        {
            try
            {
                using (var db = new LiteDatabase(new ConnectionString() { Filename = dbFile, Password = password }))
                {
                    db.GetCollectionNames();

                    LocalUser.DbFilePath = dbFile;
                    LocalUser.Password = password;
                    Setting.System.DbFilePath = dbFile;
                    return new Tuple<int, string>(1, "登录成功");
                }
            }
            catch (LiteException liteException)
            {
                if (liteException.ErrorCode == LiteException.DATABASE_WRONG_PASSWORD)
                {
                    return new Tuple<int, string>(0, "密码错误");
                }
                if (liteException.ErrorCode == LiteException.INVALID_DATABASE)
                {
                    return new Tuple<int, string>(0, "选择的不是数据库文件");
                }
                else
                {
                    return new Tuple<int, string>(2, liteException.Message);
                }
            }
            catch (Exception ex)
            {
                return new Tuple<int, string>(2, ex.Message);
            }
        }



        /// <summary>
        /// 新用户
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public Tuple<bool, string> NewUser(string password)
        {
            try
            {
                string defaultDbPath = Path.Combine(GlobalData.LocalUserDirectory, GlobalData.AppDbName);//默认数据库路径

                if (File.Exists(defaultDbPath))
                {
                    //如果默认文件已存在，则新建一个
                    defaultDbPath = Path.Combine(GlobalData.LocalUserDirectory, GlobalData.AppName_en, DateTime.Now.DateTimeString(false) + GlobalData.AppDbFileExtension);
                }
                using (var db = new LiteDatabase(new ConnectionString() { Filename = defaultDbPath, Password = password }))//如果数据库不存在，LiteDb会自动创建数据库
                {
                    db.GetCollectionNames();
                    LocalUser.DbFilePath = defaultDbPath;
                    LocalUser.Password = password;
                    Setting.System.DbFilePath = defaultDbPath;
                    return new Tuple<bool, string>(true, "新建用户成功");
                }
            }
            catch (Exception ex)
            {
                return new Tuple<bool, string>(false, ex.Message);
            }
        }

        /// <summary>
        /// 解锁
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public Tuple<int, string> UnLock(string password)
        {
            try
            {
                using (var db = new LiteDatabase(new ConnectionString() { Filename = LocalUser.DbFilePath, Password = password }))
                {
                    db.GetCollectionNames();
                    return new Tuple<int, string>(1, "解锁成功");
                }
            }
            catch (LiteException liteException)
            {
                if (liteException.ErrorCode == LiteException.DATABASE_WRONG_PASSWORD)
                {
                    return new Tuple<int, string>(0, "密码错误");
                }
                else
                {
                    return new Tuple<int, string>(2, liteException.Message);
                }
            }
            catch (Exception ex)
            {
                return new Tuple<int, string>(2, ex.Message);
            }
        }


        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="oldPassword"></param>
        /// <param name="newPassword"></param>
        /// <returns></returns>
        public Tuple<int, string> UpdatePassword(string oldPassword, string newPassword)
        {
            try
            {
                //这里严谨一点，用原密码连接下数据库
                using (var db = new LiteDatabase(new ConnectionString() { Filename = LocalUser.DbFilePath, Password = oldPassword }))
                {
                    db.Shrink(newPassword);//修改密码
                }

                LocalUser.Password = newPassword;//密码修改完成后，更新下全局的密码

                return new Tuple<int, string>(1, "密码修改成功");
            }
            catch (LiteException liteException)
            {
                if (liteException.ErrorCode == LiteException.DATABASE_WRONG_PASSWORD)
                {
                    return new Tuple<int, string>(0, "原密码错误");
                }
                else
                {
                    return new Tuple<int, string>(2, liteException.Message);
                }
            }
            catch (Exception ex)
            {
                return new Tuple<int, string>(2, ex.Message);
            }
        }

        #region 自动登录

        /// <summary>
        /// 保存登录密码
        /// </summary>
        /// <param name="password"></param>
        public void SavePassword(string password)
        {
            if (string.IsNullOrEmpty(password)) return;

            string encryptStr = password.DesEncrypt(GlobalData.AppName_en);

            FileHelper.WriteFile(Path.Combine(GlobalData.LocalUserDirectory, "autologing"), encryptStr);
        }


        /// <summary>
        /// 获取登录密码
        /// </summary>
        /// <returns></returns>
        public string GetPassword()
        {
            try
            {
                if (!File.Exists(Path.Combine(GlobalData.LocalUserDirectory, "autologing"))) return string.Empty;

                string encryptStr = FileHelper.ReadFile(Path.Combine(GlobalData.LocalUserDirectory, "autologing"));

                return encryptStr.DesDecrypt(GlobalData.AppName_en);
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLog(ex);
                return string.Empty;
            }
        }

        #endregion 自动登录
    }
}
